package com.starblink.login.editpersonalinfo.ui

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.apollographql.apollo3.api.Optional
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.basic.apollo.ext.ApolloValSetExt
import com.starblink.android.basic.ext.toast
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.PersonInfoModified
import com.starblink.android.basic.widget.LoadingDialogManager
import com.starblink.basic.log.SKLogger
import com.starblink.basic.util.ActivityStackManage
import com.starblink.basic.util.log.YYLogUtils
import com.starblink.rocketreserver.FetchAccountInfoQuery
import com.starblink.rocketreserver.StsUploadUserHeadImgQuery
import com.starblink.rocketreserver.UpdateAccountV2Mutation
import com.starblink.rocketreserver.type.AccountEditRequest
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import java.io.File

class EditPersonalInfoVM : BaseViewModel() {
    var newHeadImage: String? = null //新头像本地路径
    var newHeadImageUrl: String? = null //保存新头像的阿里云Url，防止重复上传图片
    val userInfoLiveData: MutableLiveData<FetchAccountInfoQuery.FetchAccountInfo> = MutableLiveData()

    /**
     * 更新个人信息
     */
    fun updatePersonalInfo(username: String, personalProfile: String) {
        // 先判断是否有修改
        var hasUpdate = false
        var newHeadImageUrlTmp: String? = null // 保存新头像URL，没有时为null，还未上传阿里云时为null
        var newUsername: String? = null // 保存新的用户名，没有时为null
        var newPersonalProfile: String? = null // 保存新的个人简介，没有时为null
        if (!newHeadImage.isNullOrEmpty()) {
            newHeadImageUrlTmp = newHeadImageUrl
            hasUpdate = true
        }
        if (UserDataCenter.getAccountInfo()?.userName != username) {
            newUsername = username
            hasUpdate = true
        }
        if (UserDataCenter.getAccountInfo()?.description != personalProfile) {
            newPersonalProfile = personalProfile
            hasUpdate = true
        }
        if (!hasUpdate) {
            toast(com.starblink.basic.style.R.string.nothing_update)
            return
        }
        viewModelScope.launch {
            // 如果用户修改了头像，并且头像尚未上传到阿里云，先将头像上传到阿里云
            if (newHeadImage != null && newHeadImageUrlTmp == null) {
                val response = SkGqlClient.skQuery(
                    StsUploadUserHeadImgQuery(),
                    showDefaultLoading = true
                )
                if (response?.data != null && response.data!!.stsUploadUserHeadImg != null) {
                    // 获取OssKey成功
                    SKLogger.e(
                        "dss",
                        "获取OssKey成功 stsUploadUserHeadImg=${response.data!!.stsUploadUserHeadImg!!.toString()}"
                    )

                    // 上传图片
                    MainScope().launch {
                        // 需要延迟一点开启，因为skQuery的关闭弹窗同样也是放在了子协程中
                        LoadingDialogManager.get()
                            .showLoading(ActivityStackManage.currentActivity())
                    }
                    val imageUrl = HeadImageOssUploader.upload(
                        File(newHeadImage),
                        response.data!!.stsUploadUserHeadImg!!
                    )
                    SKLogger.e("dss", "6上传图片isShowing=${LoadingDialogManager.get().isShowing}")
                    hideLoadDialog()
                    if (imageUrl != null) {
                        // 上传图片成功
                        SKLogger.e("dss", "OssUploader Success,imageUrl=$imageUrl")
                        newHeadImageUrl = imageUrl
                        newHeadImageUrlTmp = newHeadImageUrl
                    } else {
                        // 上传图片失败
                        SKLogger.e("dss", "OssUploader Fail")
                        toast(com.starblink.basic.style.R.string.modify_fail)
                        return@launch
                    }
                } else {
                    // 获取OssKey失败
                    SKLogger.e("dss", "StsUploadUserHeadImgQuery Fail")
                    toast(com.starblink.basic.style.R.string.modify_fail)
                    return@launch
                }
            }

            // 修改用户信息
            val response = SkGqlClient.skMutation(
                UpdateAccountV2Mutation(
                    accountEditRequest = AccountEditRequest(
                        headImage = Optional.presentIfNotNull(newHeadImageUrlTmp),
                        username = Optional.presentIfNotNull(newUsername),
                        description = Optional.presentIfNotNull(newPersonalProfile)
                    )
                ),
                showDefaultLoading = true
            )
            if (response?.data != null && response.data!!.updateAccountV2 != null) {
                if (response.data!!.updateAccountV2 == true) {
                    // 修改成功，更新本地用户信息，发送通知，关闭当前页面
                    UserDataCenter.getAccountInfo()?.let {
                        if (newHeadImageUrlTmp != null) {
                            ApolloValSetExt.setApolloVal<FetchAccountInfoQuery.FetchAccountInfo>(
                                model = it,
                                declaredField = "headImage",
                                value = newHeadImageUrlTmp
                            )
                        }
                        if (newUsername != null) {
                            ApolloValSetExt.setApolloVal<FetchAccountInfoQuery.FetchAccountInfo>(
                                model = it,
                                declaredField = "username",
                                value = newUsername
                            )
                            ApolloValSetExt.setApolloVal<FetchAccountInfoQuery.FetchAccountInfo>(
                                model = it,
                                declaredField = "userName",
                                value = newUsername
                            )
                        }
                        if (newPersonalProfile != null) {
                            ApolloValSetExt.setApolloVal<FetchAccountInfoQuery.FetchAccountInfo>(
                                model = it,
                                declaredField = "description",
                                value = newPersonalProfile
                            )
                        }
                        UserDataCenter.setAccountInfo(it)
                        UserDataCenter.getAccountInfo()?.let { account ->
                            YYLogUtils.e("用户信息修改后：${account.toString()}", "dss")
                        }
                    }
                    FlowBus.with<PersonInfoModified>(FlowConst.PERSON_INFO_MODIFIED_EVENT)
                        .post(
                            viewModelScope,
                            PersonInfoModified(newHeadImageUrlTmp, newUsername, newPersonalProfile)
                        )
                    toast(com.starblink.basic.style.R.string.modify_success)
                    ActivityStackManage.finishCurrentActivity()
                } else {
                    toast(com.starblink.basic.style.R.string.modify_fail)
                }
            }
        }
    }

    /**
     * 刷新用户信息
     */
    fun refreshUserInfo() {
        viewModelScope.launch {
            var hasUpdate = false
            var newHeadImageUrl: String? = null // 新头像URL,没有时为null
            var newUsername: String? = null // 新的用户名，没有时为null
            var newPersonalProfile: String? = null // 新的个人简介，没有时为null

            val response = SkGqlClient.skQuery(
                FetchAccountInfoQuery(
                ),
                showDefaultLoading = true
            )
            if (response?.data != null && response.data!!.fetchAccountInfo != null) {
                if (UserDataCenter.getAccountInfo()?.headImage != response.data!!.fetchAccountInfo!!.headImage) {
                    newHeadImageUrl = response.data!!.fetchAccountInfo!!.headImage
                    hasUpdate = true
                }
                if (UserDataCenter.getAccountInfo()?.userName != response.data!!.fetchAccountInfo!!.userName) {
                    newUsername = response.data!!.fetchAccountInfo!!.userName
                    hasUpdate = true
                }
                if (UserDataCenter.getAccountInfo()?.description != response.data!!.fetchAccountInfo!!.description) {
                    newPersonalProfile = response.data!!.fetchAccountInfo!!.description
                    hasUpdate = true
                }
                if (hasUpdate) {
                    SKLogger.e("dss", "用户信息有变化")
                    // 如果服务器返回用户信息有变化，修改本地数据，发送通知
                    UserDataCenter.setAccountInfo(response.data!!.fetchAccountInfo!!)
                    userInfoLiveData.postValue(response.data!!.fetchAccountInfo!!)
                    FlowBus.with<PersonInfoModified>(FlowConst.PERSON_INFO_MODIFIED_EVENT)
                        .post(
                            viewModelScope,
                            PersonInfoModified(newHeadImageUrl, newUsername, newPersonalProfile)
                        )
                }else{
                    SKLogger.e("dss", "用户信息没有变化")
                }
            }
        }
    }
}